package com.cmcc.migu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cmcc.migu.cmmon.util.FtpClientUtil;
import com.cmcc.migu.cmmon.util.HTTPUtil;
import com.cmcc.migu.cmmon.util.UIMAESUtil;
import com.cmcc.migu.common.entity.ResultObj;

/** 
 *
 * 文件服务器工具类
 * @Project: UIM-CLIENT
 * @File: FileDataClient.java 
 * @Date: 2015年5月18日 
 * @Author: shengyongfu
 * @Copyright: 版权所有 (C) 2015 中国移动 杭州研发中心. 
 *
 * @注意：本内容仅限于中国移动内部传阅，禁止外泄以及用于其他的商业目的 
 */

public class FileDataClient {
	private static Logger logger = LoggerFactory.getLogger(FileDataClient.class);
	
	/**
	 * 文件数据提供方请求上传接口
	 * @param clientUrl		访问地址
	 * @param authCode		访问者Code
	 * @param authKey		访问者密钥
	 * @param sourceCode	数据源Code
	 * @param fileName		文件名
	 * @param fileLength	文件长度
	 * @param MD5			文件校验md5码
	 * @param SHA1			文件校验sha1
	 * @param CRC32			文件校验crc32
	 * @return			失败返回 json字符串：如{"errorCode":100000,"errorMessage":"send fdGetNewFileInfo message error, sign null, sourceCode sourceCode","resultMap":null,"successSign":false}
	 * 					成功返回 json字符串：如{"uploadPassword":"5ickvz","downloadPassword":"93yq0e","serverType":"FTP","filePath":"/var/ftp/pub/mysqlftp/sourceCode/20150525","uploadUserName":"o9Vs9U","serverPort":21,"downloadUserName":"kgD9Jt"}
	 */
	public static String upload(String clientUrl, String authCode, String authKey, String sourceCode, 
			String fileName, Long fileLength, String MD5, String SHA1, String CRC32) {
		Boolean successFlag = true;
		String errMsg = "";
		if (StringUtils.isBlank(clientUrl)) {
			successFlag = false;
			errMsg = "访问地址不能为空";
		}
		if (StringUtils.isBlank(authCode)) {
			successFlag = false;
			errMsg = "访问者Code不能为空";
		}
		if(StringUtils.isBlank(authKey)){
			successFlag = false;
			errMsg = "访问者密钥不能为空";
		}
		if(StringUtils.isBlank(sourceCode)){
			successFlag = false;
			errMsg = "数据源Code不能为空";
		}
		if(StringUtils.isBlank(fileName)){
			successFlag = false;
			errMsg = "文件名不能为空";
		}
		if(fileLength == null){
			successFlag = false;
			errMsg = "文件长度不能为空";
		}
		Map<String, Object> otherMap = new HashMap<String, Object>();
		otherMap.put("sourceCode", sourceCode);
		otherMap.put("fileName", fileName);
		otherMap.put("fileLength", fileLength);
		otherMap.put("MD5", MD5);
		otherMap.put("SHA1", SHA1);
		otherMap.put("CRC32", CRC32);
		
		String cipherMessage = "";
		if(successFlag){
			try {
				cipherMessage = UIMAESUtil.encrypt(authCode, otherMap, new HashMap<String, Object>(), authKey);
			} catch (Exception e) {
				logger.error("the method upload in class FileDataClient throw Exception, clientUrl is {}, authCode is {}, authKey is {}, sourceCode is {}", clientUrl, authCode, authKey, sourceCode, e);
				successFlag = false;
				errMsg = "对请求参数进行加密时出现异常";
			}
		}
		String result = "";
		if(successFlag){
			try {
				result = HTTPUtil.fetchGetURLContent(clientUrl, "UTF-8", new NameValuePair("json", cipherMessage));
			} catch (Exception e) {
				logger.error("the method upload in class FileDataClient throw Exception, , clientUrl is {}, authCode is {}, authKey is {}, sourceCode is {}", clientUrl, authCode, authKey, sourceCode, e);
				successFlag = false;
				errMsg = "访问统一接口机失败";
			}
		}
		if(!successFlag){
			ResultObj resultObj = new ResultObj();
			resultObj.setSuccessSign(successFlag);
			resultObj.setErrorCode(100000);
			resultObj.setErrorMessage(errMsg);
			result = JSONObject.fromObject(resultObj).toString();
		}
		return result;
		
	}
	
	/**
	 * 文件数据提供方上传完成通知接口机接口
	 * @param clientUrl		请求地址
	 * @param authCode		访问者code
	 * @param authKey		访问者密钥
	 * @param sourceCode	数据源code
	 * @param fileID		本次文件上传任务ID
	 * @return
	 */
	public static String success(String clientUrl, String authCode, String authKey, String sourceCode, String fileID){
		Boolean successFlag = true;
		String errMsg = "";
		if(StringUtils.isBlank(clientUrl)){
			successFlag = false;
			errMsg = "访问地址不能为空";
		}
		if(StringUtils.isBlank(authCode)){
			successFlag = false;
			errMsg = "访问者Code不能为空";
		}
		if(StringUtils.isBlank(authKey)){
			successFlag = false;
			errMsg = "访问者密钥不能为空";
		}
		if(StringUtils.isBlank(sourceCode)){
			successFlag = false;
			errMsg = "数据源Code不能为空";
		}
		if(StringUtils.isBlank(fileID)){
			successFlag = false;
			errMsg = "本次上传任务的ID不能为空";
		}
		Map<String, Object> otherMap = new HashMap<String, Object>();
		otherMap.put("sourceCode", sourceCode);
		otherMap.put("recordId", fileID);
		String cipherMessage = "";
		if(successFlag){
			try {
				cipherMessage = UIMAESUtil.encrypt(authCode, otherMap, new HashMap<String, Object>(), authKey);
			} catch (Exception e) {
				logger.error("the method success in class FileDataClient throw Exception, clientUrl is {}, authCode is {}, authKey is {}, sourceCode is {}， fileID is {}", clientUrl, authCode, authKey, sourceCode, fileID, e);
				successFlag = false;
				errMsg = "对请求参数进行加密时出现异常";
			}
		}
		String result = "";
		if(successFlag){
			try {
				result = HTTPUtil.fetchGetURLContent(clientUrl, "UTF-8", new NameValuePair("json", cipherMessage));
			} catch (Exception e) {
				logger.error("the method success in class FileDataClient throw Exception, , clientUrl is {}, authCode is {}, authKey is {}, sourceCode is {}, fileID is {}", clientUrl, authCode, authKey, sourceCode, fileID, e);
				successFlag = false;
				errMsg = "访问统一接口机失败";
			}
		}
		if(!successFlag){
			ResultObj resultObj = new ResultObj();
			resultObj.setSuccessSign(successFlag);
			resultObj.setErrorCode(100000);
			resultObj.setErrorMessage(errMsg);
			result = JSONObject.fromObject(resultObj).toString();
		}
		return result;
		
	}
	
	/**
	* Description: 向FTP服务器上传文件
	* @Version1.0 
	* @param url FTP服务器hostname
	* @param port FTP服务器端口
	* @param username FTP登录账号
	* @param password FTP登录密码
	* @param path FTP服务器保存目录
	* @param filename 上传到FTP服务器上的文件名
	* @param localFilePath 本地文件路径
	* @return 成功返回true，否则返回false
	*/ 
	public static boolean uploadFile(String url,Integer port,String username,String password,String path, String filename, String localFilePath) {
		FtpClientUtil ftpClient = new FtpClientUtil(url, port, username, password);
		Boolean retFlag = false;
		try {
			if (ftpClient.open()) {
				File file = new File(localFilePath);
				InputStream input = new FileInputStream(file);
				retFlag = ftpClient.uploadFile(path, filename, input);
			}
		}catch(Exception ex){
			logger.error("run fileUpload error:"+ex.getMessage(),ex);
		}finally{
			ftpClient.close();
		}
		return retFlag;
	}
	
	/**
	 * 从服务器下载文件
	 * @param url	FTP服务器hostname
	 * @param port	FTP服务器端口
	 * @param username	FTP服务器用户名
	 * @param password	FTP服务器密码
	 * @param remoteFilenPath ftp服务器路径+文件名
	 * @param localFilePath	下载目的位置(路径+文件名)
	 * @return 成功返回true，否则返回false
	 */
	public static boolean downloadFile(String url,Integer port,String username,String password,String  remoteFilenPath, String localFilePath){
		FtpClientUtil ftpClient = new FtpClientUtil(url, port, username, password);
		Boolean retFlag = false;
		try {
			if (ftpClient.open()) {
				ftpClient.get(remoteFilenPath, localFilePath);
				retFlag = true;
			}
		}catch(Exception ex){
			logger.error("run fileUpload error:"+ex.getMessage(),ex);
		}finally{
			ftpClient.close();
		}
		return retFlag;
	}

}
